import mysql from 'mysql';

class MySQLInfo {
    // class methods
    constructor(host,port,dbUser,dbPwd,dbName) {
        this.connection =  mysql.createConnection({
            host     : host,
            port     : port,
            user     : dbUser,
            password : dbPwd,
            database : dbName
        });
        this.dbName = dbName
    }

    getTableInfo() {
        return new Promise((resolve, reject) => {
            this.connection.connect(err => {
                if(err) return reject("数据库连接失败，请检查数据库连接！")
            });
            let sql = `SELECT table_name tableName,table_comment tableComment
                        FROM information_schema.tables
                        WHERE table_schema = ? 
                        AND (table_type = 'base table' OR table_type = 'BASE TABLE')`;

            this.connection.query(sql, this.dbName,
                function (error, results, fields) {
                    if (error) {
                        return reject(error);
                    } else {
                        return resolve(JSON.parse(JSON.stringify(results)))
                    }
                })
            this.connection.end(function (err) {
                if(err) return reject("数据库关闭失败！")
            })
        })

    }


    getColumnInfo(tableName) {
        return new Promise((resolve, reject) => {
            this.connection.connect(err => {
                if(err) return reject("数据库连接失败，请检查数据库连接！")
            });
            let sql = `SELECT  ordinal_position orderArrange,table_schema dbName,table_name tableName,
                       column_name columnName,data_type columnType,is_nullable isNullable,
                       character_maximum_length maximumLength,column_comment columnComment
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE table_name = ? 
                AND table_schema = ? 
                ORDER BY table_schema,table_name,ordinal_position`;

            this.connection.query(sql,[tableName,this.dbName],
                function (error, results, fields) {
                    if (error) {
                        return reject(error);
                    } else {
                        return resolve(JSON.parse(JSON.stringify(results)))
                    }
                })
            this.connection.end(function (err) {
                if(err) return reject("数据库关闭失败！")
            })
        })

    }

}


export default MySQLInfo

